package edu.cmu.ece.ds.droidchat;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.ece.ds.droidchat.controller.ChatSessionListBaseAdapter;
import edu.cmu.ece.ds.droidchat.model.ChatSessionInfo;
import edu.cmu.ece.ds.droidchat.model.StringConstants;
import edu.cmu.ece.ds.droidchat.util.Toolbox;

public class ChatSessionsListActivity extends ListActivity {

    private static final String TAG = "ChatSessionsListActivity";
    private ListView lv;
    private static ArrayList<ChatSessionInfo> mChatSessionArray;
    private ChatSessionListBaseAdapter mChatSessionListBaseAdapter;

    private ServiceMessageReceiver mReceiver; // the BroadcastReceiver component

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mChatSessionArray = new ArrayList<ChatSessionInfo>();
        mChatSessionListBaseAdapter = new ChatSessionListBaseAdapter(this,
                mChatSessionArray);

        setListAdapter(mChatSessionListBaseAdapter);

        lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setDivider(null);
        lv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        lv.setCacheColorHint(Color.WHITE);

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                TextView tv = (TextView) ((LinearLayout) view)
                        .findViewById(R.id.chat_session_name);
                // When clicked, show a toast with the TextView text
                /*Toast.makeText(getApplicationContext(), tv.getText(),
                        Toast.LENGTH_SHORT).show();*/
                Log.e(TAG,
                        "session id = "
                                + ((ChatSessionInfo) mChatSessionListBaseAdapter
                                        .getItem(position)).getSessionid());
                TextView infoLine = (TextView) ((LinearLayout) view)
                        .findViewById(R.id.chat_session_info);
                if (infoLine.getVisibility() != View.GONE) {
                    // either pending for my response, or waiting for response.
                    if (mChatSessionArray.get(position)
                            .isPendingForMyInvitation()) {
                        Log.e(TAG, "pending for my invitation");
                        Toolbox.returnToChatWindowActivity(
                                ChatSessionsListActivity.this,
                                ((ChatSessionInfo) mChatSessionListBaseAdapter
                                        .getItem(position)).getSessionid());
                    } else if (mChatSessionArray.get(position)
                            .isPendingForMyResponse()) {
                        Log.e(TAG, "waiting for my response");
                        Toolbox.returnToChatWindowActivity(
                                ChatSessionsListActivity.this,
                                ((ChatSessionInfo) mChatSessionListBaseAdapter
                                        .getItem(position)).getSessionid());
                    } else {
                        Log.e(TAG, "WTF?");
                    }
                } else {
                    Toolbox.returnToChatWindowActivity(
                            ChatSessionsListActivity.this,
                            ((ChatSessionInfo) mChatSessionListBaseAdapter
                                    .getItem(position)).getSessionid());
                }
            }
        });

        Log.e(TAG, "registering broadcast receiver");
        mReceiver = new ServiceMessageReceiver();
        IntentFilter filter = new IntentFilter();
        // only care about broadcast "ACTION_FOR_CHAT_SESSION_LIST_ACTIVITY"
        filter.addAction(StringConstants.ACTION_FOR_CHAT_SESSION_LIST_ACTIVITY);
        this.registerReceiver(mReceiver, filter);

        // am i invited?
        Intent i = getIntent();
        if (i.getBooleanExtra(StringConstants.EXTRA_IS_INVITED, false)) {
            Log.e(TAG, "invited to start this activity");
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "---onDestroy---");
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "---onStart---");
        // real chat sessions
        mChatSessionArray.clear();
        mChatSessionArray.addAll(Toolbox.getAllChatSessions());
        Log.e(TAG, "mChatSessionArray HAS " + mChatSessionArray.size()
                + " sessions");
        mChatSessionListBaseAdapter.notifyDataSetChanged();
    }


    /*@Override
    protected void onResume() {
    	super.onResume();
    	Log.d(TAG, "---onResume---");
    	
    	// real chat sessions
        mChatSessionArray.clear();
        mChatSessionArray.addAll(Toolbox.getAllChatSessions());
        Log.e(TAG,"mChatSessionArray HAS " +mChatSessionArray.size()+" sessions");
        mChatSessionListBaseAdapter.notifyDataSetChanged();
    }*/
    
    private class ServiceMessageReceiver extends BroadcastReceiver {
        //public static final String TAG = "ServerMessageReceiver";

        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent);

            boolean refreshList = intent.getBooleanExtra(
            		StringConstants.EXTRA_REFRESH_LIST, false);
            
            if ( refreshList==false ){
            	// the Chat Session that potentially has new messages to be
            	// displayed
            	String chatSessionID = intent
                    .getStringExtra(StringConstants.EXTRA_CHAT_SESSION_ID);
            	ChatSessionInfo ch = Toolbox.getChatSession(chatSessionID);
            	int unreadMsgCnt = ch.getNewMessagesCount();
            	if(unreadMsgCnt>0){
            		updateNewMessagePendingStatus(chatSessionID, true, unreadMsgCnt);
            	}
            } else {
            	// need to refresh the chat session list display
            	//  because some chat session invitation response has just 
            	//  came back
            	
            	// check the latest response causes a 1-on-1 chat session to die
            	String chatSessionID = intent
                .getStringExtra(StringConstants.EXTRA_CHAT_SESSION_ID);
            	ChatSessionInfo chInfo = Toolbox.getChatSession(chatSessionID);
            	
            	if(chInfo!=null){
            		if (chInfo.numberOfParticipants() == 0) {
            			/*if(chInfo.isPendingForMyInvitation()==false){
            				Log.e(TAG + "onReceive()", "# of participants is zero -> removing chat session");
                        	//Toolbox.removeChatSession(chInfo.getSessionid());
            				Toolbox.removeChatSession(chInfo.getSessionid(), true);
            			}*/
            			Toolbox.removeChatSession(chInfo.getSessionid(), false);
                    }
            	}
            	
            	//String chatSessionID = intent
                //.getStringExtra(StringConstants.EXTRA_CHAT_SESSION_ID);
            	mChatSessionArray.clear();
                mChatSessionArray.addAll(Toolbox.getAllChatSessions());
                Log.e(TAG, "mChatSessionArray HAS " + mChatSessionArray.size()
                        + " sessions");
                mChatSessionListBaseAdapter.notifyDataSetChanged();
            }
        }

    }

    public void updateNewMessagePendingStatus(String chatSessionID,
            boolean isPending, int unreadMessageCount) {
        int position = mChatSessionListBaseAdapter
                .getPositionInList(chatSessionID);
        
        System.out.println("updateNewMessagePendingStatus()");
        System.out.println("chatSessionID=" + chatSessionID);
        System.out.println("unreadMessageCount" + unreadMessageCount);
        
        if (position == -1) {
            Log.e(TAG, "chat session not found with id=" + chatSessionID);
        } else {
        	
        	if(lv==null){
        		Log.e(TAG, "lv is null");
        		return;
        	}else if(lv.getChildAt(position)==null){
        		Log.e(TAG, "position=" + position);
        		Log.e(TAG, "lv.getChildAt(position) is null");
        		return;
        	}else if(lv.getChildAt(position).getTag()==null){
        		Log.e(TAG, "lv.getChildAt(position).getTag() is null");
        		return;
        	}
        	((ChatSessionListBaseAdapter.ViewHolder) lv.getChildAt(position)
        			.getTag()).showNewMessagePendingImageView(isPending,
                    unreadMessageCount);
        }
    }

}
